//
//  XYReadModel.swift
//  XYReadBook
//
//  Created by fox on 2017/9/28.
//  Copyright © 2017年 tsaievan. All rights reserved.
//

import UIKit

class XYReadModel: NSObject {
    lazy  private(set) var index: Int = {
           let chapterIndex = self.bookID + "index"
        let indexValue = UserDefaults.standard.object(forKey: chapterIndex)as? Int
        XYLog(messsage: indexValue)
        return indexValue ?? 0
    }()
    let lastChapter = XYReadChapterModel()
    let currentChapter = XYReadChapterModel()
    let nextChapter = XYReadChapterModel()

    let bookID:String
    /// 章节数组
    var chapters:[Chapters] = []

    init(bookID:String) {
        self.bookID = bookID
        super.init()
    }


    deinit {
//        let chapterIndex = bookID + "index"
//        XYLog(messsage: "👻我死了BookReadModel")
//        UserDefaults.standard.set(index, forKey: chapterIndex)
//        XYLog(messsage: index)
    }


    func updateIndex(_ index: Int, with callback: (()->())?) {
//        HUDManager.xwj_show()
        self.index = index
        loadData(callBack: callback)
//        HUDManager.xwj_hide()
    }

    func gotoNextChapter() {
        index += 1
        updateIndex(index, with: nil)
    }

    func gotoLastChapter() {
        index -= 1
        updateIndex(index, with: nil)
    }

    /// 下载
    func downloadData(downIndex:Int,callback: (()->())?) {
        if downIndex > 0 && downIndex < self.chapters.count - 1{
            download(downIndex:downIndex,callBack: callback)
        }
    }

    //  第一次加载
    func download(downIndex:Int,callBack:(()->())?) {
        
        let curentLink = self.chapters[downIndex].link.urlEncode
        currentChapter.url = BaseUrl.chapter.rawValue + curentLink!
        currentChapter.bookID = bookID
        currentChapter.loadData { (isSuccess) in
            if isSuccess {
                callBack?()
            }
        }
    }



    //  第一次加载
    func loadData(callBack:(()->())?) {


        if index > 0 {
            /// 是为了防止切换源功能的时候,假如用户最后一次点的是1500章
            /// 而且 换源的最大章节数 是1400 章
            // 那么按照原来的index岂不是会出问题??? 无意外,数组越界崩溃.嘎嘎嘎(づ￣3￣)づ╭❤～
            if index > self.chapters.count - 1 {
                index = chapters.count - 1
            }
            let link = self.chapters[index - 1].link.urlEncode
            let titleString = chapters[index - 1].title
            lastChapter.titleString = titleString
            lastChapter.url = BaseUrl.chapter.rawValue + link!
            lastChapter.bookID = bookID
            lastChapter.loadData {_ in }
        }

        let curentLink = self.chapters[index].link.urlEncode
        currentChapter.url = BaseUrl.chapter.rawValue + curentLink!
        currentChapter.bookID = bookID
        let titleString = chapters[index].title
        currentChapter.titleString = titleString
        currentChapter.loadData { isSuccess in
            if isSuccess {
                callBack?()
            }
        }

        if index < chapters.count - 1 {
            let nextChapterLink = self.chapters[index + 1].link.urlEncode
            nextChapter.url = BaseUrl.chapter.rawValue + nextChapterLink!
            nextChapter.bookID = bookID
            let titleString = chapters[index + 1].title
            nextChapter.titleString = titleString
            nextChapter.loadData {_ in }
        }
    }


    
    /*
     切换源数据章节
     // 范例
     http://api.zhuishushenqi.com/atoc?view=summary&book=51d11e782de6405c45000068
     
     请求切换源后的目录
     http://api.zhuishushenqi.com/btoc/56f28f3ed1f822614cff4460?view=chapters
     
     old之前请求源的数据
     http://api.zhuishushenqi.com/mix-atoc/5224a6db3d25dae84b0003a8?bookId=5224a6db3d25dae84b0003a8
     
     
     两个章节请求的URL不一样
     
     */
func  getchapterList(compeleted: @escaping ([Chapters]?, Error?)->()) {

    // 第一步,判断有无网络,如果无网络,加载缓存数据,如果缓存数据没有,则展示无数据页
    // 如果有网络,则加载最新数据.接着缓存数据.
        // 证明无网络
        // http://api.zhuishushenqi.com/mix-atoc/51d11e782de6405c45000068?bookId=51d11e782de6405c45000068
        let dict = ["bookId":bookID] as [String : Any]
        let url = BaseUrl.defult.rawValue + "mix-atoc/" + bookID
        HTTPManager.requestModel(url: url, method: .get, parameters: dict, iscaChe: true) { (resp:XYChapterListModel?, error) in
            if let resp = resp {
                if let chapters = resp.mixToc?.chapters {
                    self.chapters.removeAll()
                    self.chapters = chapters
                    compeleted(chapters,nil)
                }
            }else {
                compeleted(nil,nil)
            }
        }
    }



/*
        /// 在这里做分支判断.判断是否是切换源后的章节目录
        let soureStrBookID = String.init(format: "%@ChangeSoureBookID", bookID)
    // TODO 这里有Bug回头在修复
        let contain = HTTPCache.xwj_containsObject(forKey: soureStrBookID)
        if contain == true {
            /// 证明是切换过源数据的 那么按照新的方式去获取数据
            let bookIDString = HTTPCache.xwj_objectForKey(forkey: soureStrBookID)as! String
            let urlString = BaseUrl.defult.rawValue + "btoc/" + bookIDString

            let urlStringKey = urlString + "chapters"
            let dict = ["view":"chapters"] as [String:Any]
            HTTPManager.requestModel(url: urlString, method: .get, parameters: dict, iscaChe: false, compeleted: { (resp:MixToc?, error) in

                
                if let resp = resp {
                    
                    self.chapters.removeAll()
                    self.chapters = resp.chapters
                    /// 自己缓存
                    HTTPCache.store(resp, forKey: urlStringKey)
                    compeleted(resp.chapters,nil)
                }else {
                    compeleted(nil,nil)
                }
            })
        }else {

            let dict = ["bookId":bookID] as [String : Any]
            let url = BaseUrl.defult.rawValue + "mix-atoc/" + bookID
            let urlKey = url + "chapters"
            HTTPManager.requestModel(url: url, method: .get, parameters: dict, iscaChe: false) { (resp:XYChapterListModel?, error) in
                
                if let resp = resp {
                    if let chapters = resp.mixToc?.chapters {
                        self.chapters.removeAll()
                        self.chapters = chapters
                        /// 自己缓存
                        HTTPCache.store(resp, forKey: urlKey)
                        compeleted(chapters,nil)
                    }
                    
                }else {
                    compeleted(nil,nil)
                }
            }
        }

 */


}
